package com.web.controller;

import com.alibaba.fastjson2.JSON;
import com.web.entity.ResponseResult;
import com.web.util.OssUtils;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 文件上传servlet
 */
@WebServlet("/upload")
public class FileUploadServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建文件上传对象
        ServletFileUpload upload = new ServletFileUpload();
        //限制文件大小
        upload.setFileSizeMax(10 * 1024 * 1024);
        //判断请求中是否有文件内容
        if(ServletFileUpload.isMultipartContent(req)){
            try {
                //获得文件项目迭代器
                FileItemIterator itemIterator = upload.getItemIterator(req);
                //遍历迭代器
                while(itemIterator.hasNext()){
                    //获得文件内容
                    FileItemStream stream = itemIterator.next();
                    //上传OSS 1.文件流 2.文件名
                    OssUtils.upload(stream.openStream(),stream.getName());
                    //获得文件地址
                    String url = OssUtils.getURL(stream.getName());
                    //把地址发送给前端
                    resp.getWriter().write(JSON.toJSONString(new ResponseResult(200,"OK",url)));
                }
            } catch (FileUploadException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
